package ldh.im.fxbase.util;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class  NettyClientFactory {

    private static NettyClientFactory instance = null;
    private Map<String, Channel> fileServerMap = new ConcurrentHashMap<>();

    private volatile Channel clientChannel = null;

    private NettyClientFactory() {

    }

    public static NettyClientFactory getInstance() {
        if (instance == null) {
            synchronized (NettyClientFactory.class) {
                if (instance == null) {
                    instance = new NettyClientFactory();
                }
            }
        }
        return instance;
    }

    public void sendFile(String host, int port, Long userId, String mId, String file) {
        ThreadPoolUtil.submit(()->{
            Channel channel = getClientChannel(host, port);
//            TransferFile transferFile = new TransferFile(userId, mId, file);
//            channel.write(transferFile);
        });
    }

    public Channel getClientChannel(String host, int port) {
        String key = host + "_:_" + port;
        Channel channel = fileServerMap.get(key);
        if (channel == null) {
            activeClientChannel(host, port);
        } else {
            if (!channel.isActive()) {
                remove(key);
                activeClientChannel(host, port);
            }
        }
        return fileServerMap.get(key);
    }

    public void activeClientChannel(String host, int port) {
        if (clientChannel == null) {
            synchronized (NettyClientFactory.class) {
                if (clientChannel == null) {
                    initClientChannel(host, port);
                }
            }
        }
    }

    private void remove(String key) {
        fileServerMap.remove(key);
    }

    private void initClientChannel(String host, int port) {
        String key = host + "_:_" + port;
        EventLoopGroup workerGroup = new NioEventLoopGroup(1);
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup);
            b.channel(NioSocketChannel.class);
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                }
            });

            ChannelFuture f = b.connect(host, port).sync();
            f.channel().closeFuture().addListener(ff->{
                remove(key);
            });
            fileServerMap.put(key, f.channel());
            f.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
